package com.chen.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.Result;
import com.chen.mapper.RoleMapper;
import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.pojo.UserRole;
import com.chen.pojo.bean.UserInfo;
import com.chen.service.Impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenchao
 */
@RestController
@RequestMapping("/person")
@Api(value = "UserController", tags = "用户操作")
public class UserController {

    @Resource
    private UserServiceImpl userService;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserMapper userMapper;

    //更新
    @PutMapping("/updateUser")
    @ApiOperation("更新")
    public Result<?> updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @PostMapping("/save")
    public Boolean save(@RequestBody User users) {
        return userService.saveUser(users);
    }


    //    分页查询
    @GetMapping("/page")
    public IPage<User> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String nick) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrqpper = new QueryWrapper<>();

        if (!"".equals(username)) {
            queryWrqpper.like("username", username);
        }
        if (!"".equals(nick)) {
            queryWrqpper.like("nick", nick);
        }
        queryWrqpper.orderByDesc("id");
        IPage<User> userPage = userService.page(page, queryWrqpper);
        return userPage;


    }

    //    删除
    @DeleteMapping("/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id) {
        return userService.removeById(id);
    }



    //导出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("introduce", "个性签名");
        writer.addHeaderAlias("regtime", "注册时间");
        writer.addHeaderAlias("sex", "性别");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("nick", "昵称");
        writer.addHeaderAlias("avatar", "头像");
        writer.addHeaderAlias("address", "地址");


        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    //更新
    @PutMapping("/changeRole")
    @ApiOperation("更新权限菜单")
    public Result<?> changeRole(@RequestBody User user) {
        // 先根据角色id删除所有的角色跟权限的绑定关系
        roleMapper.deleteRoleByUserId(user.getId());
        // 再新增 新的绑定关系
        for (Integer roleId : user.getRoles()) {
            roleMapper.insertUserRole(user.getId(), roleId);
        }

        // 获取当前登录用户的角色id列表
        UserInfo currentUser = new UserInfo();
        // 如果当前登录用户的角色列表包含需要修改的角色id，那么就重新登录
        if (user.getId().equals(currentUser.getId())) {
            return Result.success(true);
        }
//        如果不包含，则返回false，不需要重新登录。
        return Result.success(false);
    }

    @GetMapping("/selectBook")
    @ApiOperation("多表查询")
    public Result<?> findPages(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(User::getUsername, search);
        }

//        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), search);
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        for (User record : userPage.getRecords()) {
            List<UserRole> roles = roleMapper.getByUserRoleUserId(record.getId());
            List<Integer> roleIds = roles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            record.setRoles(roleIds);
        }
        return Result.success(userPage);
    }


    @GetMapping("/selectOne/{id}")
    public Result selectOne(@PathVariable("id") int id){
        User user = userMapper.selectOne1(id);
        UserInfo info=new UserInfo(user);
        return Result.success(info);
    }


    @GetMapping("/UserCounts")
    @ApiOperation("人数")
    public Result getUserCounts(){
        return  Result.success(userMapper.UserCounts());
    }

}
